package org.example.syn;

/**
 * @author Yyming
 * @version 10.0
 * Created by Yyming on 2020/8/10
 */

import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

/**定义限额注解*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface BankTransferMoney {
    double maxMoney() default 10000;
}
/**转账处理业务类*/
public class BankService {
    /**
     * @param money 转账金额
     */
    @BankTransferMoney(maxMoney = 15000)
    public static void TransferMoney(double money){
        System.out.println(processAnnotationMoney(money));

    }
    private static String processAnnotationMoney(double money) {
        try {
            Method transferMoney = BankService.class.getDeclaredMethod("TransferMoney",double.class);
            boolean annotationPresent = transferMoney.isAnnotationPresent(BankTransferMoney.class);
            if(annotationPresent){
                BankTransferMoney annotation = transferMoney.getAnnotation(BankTransferMoney.class);

                double v = annotation.maxMoney();
                System.out.println(v);
                InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
                Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
                memberValues.setAccessible(true);
                Map map = (Map) memberValues.get(invocationHandler);
                map.put("maxMoney",12000.00);
                double l = annotation.maxMoney();
                if(money>l){
                    return "转账金额大于限额，转账失败";
                }else {
                    return"转账金额为:"+l+"，转账成功";
                }
            }
        } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return "转账处理失败";
    }

    /**
     * 测试{@code@BankTransferMoney}
     * @param args
     */
    public static void main(String[] args){
        TransferMoney(10000);
    }
}

